<?php

namespace App\Http\Controllers\Client\Activity;

use App\Http\Controllers\ClientController;
use App\Jobs\LotteryDraw;
use App\Models\Activity;
use App\Models\Common\Common;
use App\Models\Common\Wechat;
use App\Models\Tools\Data;
use App\Models\Tools\Period;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LotteryParticipateController extends ClientController
{
    /**
     * 参与抽奖活动
     */
    public function index()
    {

        $all = $this->all;
        $act_id = $all['act_id'];

        try{
            // 检查是否关注了公众号：如果没有关注公众号，跳转到一个专属二维码链接，关注后再次弹出这个链接
            $app = Wechat::officialAccount();
            $user = $app->user->get($this->openid);
            if($user['subscribe'] === 0){
                return $this->setReturnJson(-3,'请先关注公众号再参与');
            }

            // 检查账号信息
            $talent = DB::table('talent')->where('we_id','=',$this->we_id)->first();
            $talent = json_decode(json_encode($talent), true);
            // 达人注册信息
            if(!$talent){
                return $this->setReturnJson(-2, '您未来飞网绑定达人信息，是否前往绑定？');
            }
            // 达人状态
            if($talent['status'] !== Data::DATA_DB_TALENT_STATUS_SUCCESS){
                return $this->setReturnJson(-1, '参与失败，您的账号还未通过来飞网的审核，您可在工作时间联系公众号在线客服为您加速审核');
            }

        }catch (\Exception $e){
            Log::error(LotteryParticipateController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '参与失败');
        }

        try {
            DB::beginTransaction();
            // 查询活动信息
            $activity = DB::table('lottery_activity')->where('act_id', '=', $act_id)->lockForUpdate()->first();
            $activity = json_decode(json_encode($activity), true);
            // 查询活动详情
            if ($activity['status'] !== Data::DATA_DB_LOTTERY_ACTIVITY_STATUS_BEFORE) {
                DB::rollBack();
                return $this->setReturnJson(-1, '参与失败，活动已达到参与人数上限或已截止');
            }
            // 活动是否还在开启
            if ($activity['is_stop'] === 1) {
                DB::rollBack();
                return $this->setReturnJson(-1, '此活动已被关闭');
            }
            // 查询达人常住地是否和店铺所在位置相同
            $shop_message = DB::table('shop')->where('shop_id','=',$activity['shop_id'])->first();
            $shop_message = json_decode(json_encode($shop_message), true);
            if($talent['city'] !== $shop_message['city']){
                DB::rollBack();
                return $this->setReturnJson(-1,'参与失败，您的常住城市与店铺所在城市不同');
            }

            // 检查用户是否中奖过啊当前店铺的其他团购，如果中过奖不能再次参与
            $winners = DB::table('lottery_activity as la')
                ->leftJoin('lottery_draw_detail as ldd','ldd.act_id','=','la.act_id')
                ->where('la.shop_id','=',$activity['shop_id'])
                ->pluck('ldd.we_id')
                ->toArray();
            if(in_array($this->we_id, $winners)){
                DB::rollBack();
                return $this->setReturnJson(-1,'您已经赢得过此店铺的团购活动，不可以重复参与哦');
            }

            // 检查参与状态:如果已经参与过当前团购的抽奖，不允许再参与
            $participate = DB::table('lottery_users_draw as lud')
                ->leftJoin('lottery_activity as la','lud.act_id','=','la.act_id')
                ->where('lud.we_id', '=', $this->we_id)
                ->where('la.shop_id', '=', $activity['shop_id'])
                ->whereIn('la.status',[Data::DATA_DB_LOTTERY_ACTIVITY_STATUS_BEFORE, Data::DATA_DB_LOTTERY_ACTIVITY_STATUS_PRE]) // 正在进行和正在开奖状态
                ->count();
            if ($participate) {
                DB::rollBack();
                return $this->setReturnJson(-1, '您已参与此店铺的活动，请不要重复参与');
            }

            // 添加抽奖信息
            $code = Activity::getCode($activity['shop_id']);
            if(!$code){
                throw new \Exception('参与次数code超出限制');
            }
            $participate_id = DB::table('lottery_users_draw')
                ->insertGetId(['we_id' => $this->we_id, 'act_id' => $act_id, 'code' => $code,]);


            // 查询参与人数，如果超过阈值直接开奖
            $users = DB::table('lottery_users_draw')->where('act_id','=',$act_id)->count();

            $participate_number = DB::table('shop_type')
                ->where('st_id','=',$shop_message['shop_type'])
                ->value('participate_number');

            if($users >= $participate_number){
                LotteryDraw::dispatch($act_id);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error(LotteryParticipateController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '参与失败，请重试');
        }

        try {
            //发送参与成功推送
            $data = [
                'first' => '您已成功参与本次霸王餐抽奖活动，您的兑奖码是' . $code,
                'keyword1' => $this->nickname,
                'keyword2' => ['霸王餐活动 第' . $activity['act_no'] . '期', '#F00'],
                'keyword3' => date('Y-m-d H:i:s'),
                'remark' => '本期活动将在满足条件时开奖,如果您中奖将为您发送通知，届时请及时购买团购并按要求上传购买截图，超时未上传截图中奖机会将会被转移给他人，请保持关注哦~',
            ];
            //发送通知
            Common::sendLaifeiMessage($this->openid, 'participate', $data, '/lottery');
        } catch (\Exception $e) {
            Log::error(LotteryParticipateController::class, ['remark' => '活动参与成功，消息推送失败', 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '消息推送失败');
        }

        return $this->setReturnJson(0, '参与成功', [
            'participate_id' => $participate_id,
            'code' => $code,
        ]);

    }

}
